package com.hjc.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjc.oj.common.ErrorCode;
import com.hjc.oj.constant.CommonConstant;
import com.hjc.oj.exception.BusinessException;
import com.hjc.oj.judge.JudgeService;
import com.hjc.oj.judge.codesandbox.model.JudgeInfo;
import com.hjc.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.hjc.oj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.hjc.oj.model.entity.*;
import com.hjc.oj.model.enums.QuestionSubmitLanguageEnum;
import com.hjc.oj.model.enums.QuestionSubmitSatatusEnum;
import com.hjc.oj.model.vo.QuestionSubmitVO;
import com.hjc.oj.service.QuestionSubmitService;
import com.hjc.oj.service.QuestionService;
import com.hjc.oj.mapper.QuestionSubmitMapper;
import com.hjc.oj.service.UserService;
import com.hjc.oj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{

    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //判断语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum langugeEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if ((langugeEnum == null)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编程语言错误");
        }if (!langugeEnum.getValue().equals("java")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"当前仅支持java");
        }

        Long questionId  = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,ErrorCode.NOT_FOUND_ERROR.getMessage());
        }
        // 是否已已提交题目 todo连续提交
        long userId = loginUser.getId();
        //每个用户穿行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);

//      题解的题头+  用户的代码
        questionSubmit.setCode(question.getAnswer()+questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        questionSubmit.setStatus(QuestionSubmitSatatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo(JSONUtil.toJsonStr(new JudgeInfo()));
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据录入失败");
        }
        //执行判题服务 ,异步执行
        long questionSubmitId = questionSubmit.getId();
        CompletableFuture.runAsync(()->{
            judgeService.doJudge(questionSubmitId);
        });

        return questionSubmitId;
    }

    /**
     * 获取查询包装类 (用户根据那些字段查询，根据传来的请求对象，得到mybatis 框架支持的查询QueryWrapper类)
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder =questionSubmitQueryRequest.getSortOrder();

        queryWrapper.eq(ObjectUtils.isNotEmpty(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitSatatusEnum.getEnumByValue(status)!=null, "status", status);

        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取单个题目的封装类
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        System.out.println("单个提交信息脱敏->getQuestionSubmitVO"+questionSubmit.getId());
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
//        long questionSubmitId = questionSubmit.getId();
//        // 1. 关联查询用户信息
//        Long userId = questionSubmit.getUserId();
//        User user = null;
//        if (userId != null && userId > 0) {
//            user = userService.getById(userId);
//        }
//        UserVO userVO = userService.getUserVO(user);
//        questionSubmitVO.setUserVO(userVO);
        //脱敏 仅本人和管理员能看见自己提交的代码
       long userId = loginUser.getId();
       if(userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
       }
       return questionSubmitVO;
    }

    /**
     * 获取题目分页的包装类
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
//        System.out.println("脱敏->getQuestionSubmitVOPage");
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
//        int i = 0;
//        for(QuestionSubmit q:questionSubmitList){
//            System.out.println(i+"    QuestionSubmit->"+q);
//            i++;
//        }
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());


        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
//        // 1. 关联查询用户信息
//        Set<Long> userIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));
//        // 填充信息
//        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
//            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
//            Long userId = questionSubmit.getUserId();
//            User user = null;
//            if (userIdUserListMap.containsKey(userId)) {
//                user = userIdUserListMap.get(userId).get(0);
//            }
//            questionSubmitVO.setUserVO(userService.getUserVO(user));
//            return questionSubmitVO;
//        }).collect(Collectors.toList());
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit,loginUser))
                .collect(Collectors.toList());
//        System.out.println("questionSubmitList->脱敏完成");
//        System.out.println(Arrays.toString(questionSubmitVOList.toArray()));
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

}




